﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using planerka.DataAccess.ViewModels;
using System.Web;
using planerka.Common.Enums;
using planerka.DataAccess.Models;
using System.Web.Mvc;
using NLog;
using planerka.Common;

namespace planerka.DataAccess.DataService
{
    public class PaymentService
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        // получить список платежей по задаче
        public List<payment> getTaskPayments(long task_ID)
        {
            List<payment> payments = new _Repository<payment>()
                .FindAll(p => p.task_ID == task_ID).ToList();

            return payments;
        }

        // получить список моих платежей
        public List<backupPayment> getBackupPayments(long user_ID, bool clearPaymentSums = true)
        { 
            // получить список платежей для задач, в которых я администратор
            //List<long> myProject_IDs = new ProjectService().getProjectsList(user_ID).Select(p => p.ID).ToList();

            //List<backupPayment> backupPayments = new _Repository<payment>().FindAll(p => myProject_IDs.Contains(p.task.project_ID))
            //    .Select(p => new backupPayment { payment_ID = p.ID, sum = p.sumIn ?? 0 - p.sumOut ?? 0}).ToList();
            _Repository<payment> paymentRepo = new _Repository<payment>();
            List<backupPayment> backupPayments = paymentRepo.FindAll(p => p.task.project.owner_ID == user_ID)
                .Select(p => new backupPayment { payment_ID = p.ID, sum = (p.sumIn ?? 0) - (p.sumOut ?? 0) }).ToList();

            if (clearPaymentSums)
            {
                payment _payment;
                foreach (var backupPaymentsItem in backupPayments)
                {
                    _payment = paymentRepo.FindAll(p => p.ID == backupPaymentsItem.payment_ID).FirstOrDefault();
                    if (_payment != null)
                    {
                        _payment.sumIn = null;
                        _payment.sumOut = null;


                    }
                }

                try
                {
                    paymentRepo.Save();
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(logger, ex,
                        "public List<backupPayment> getBackupPayments(long user_ID, bool clearPaymentSums = true)",
                        "Ошибка обнуления данных платежей");
                }
            }

            return backupPayments;
        }

        // восстановить платеж
        public bool restorePayment(long user_ID, backupPayment _backupPayment)
        {
            bool success = true;
            _Repository<payment> paymentRepo = new _Repository<payment>();
            payment _payment = paymentRepo
                .FindAll(p => p.ID == _backupPayment.payment_ID
                && p.task.project.owner_ID == user_ID /* а того ли пользователя платеж? */).FirstOrDefault();
            
            if (_payment != null)
            {
                if (_backupPayment.sum > 0)
                {
                    _payment.sumIn = _backupPayment.sum;
                    _payment.sumOut = null;
                }
                else 
                {
                    _payment.sumOut = - _backupPayment.sum;
                    _payment.sumIn = null;
                }

                try { paymentRepo.Save(); }
                catch (Exception ex)
                {
                    success = false;
                    ExceptionUtility.LogException(logger, ex,
                                    "public bool restorePayment(long user_ID, backupPayment _backupPayment)",
                                    "Ошибка восстановления платежа:  _backupPayment.payment_ID" + _backupPayment.payment_ID + " , _backupPayment.sum: " + _backupPayment.sum);
                }
            }

            return success;
        }
    }
}
